<template>
  <el-upload :file-list="fileList" list-type="picture-card" :http-request="handleUpload" ref="uploadRef">
    <template #trigger>
      <div class="flex column">
        <my-icon icon="el-Plus" ref="handleUploadRef" />
        <span style="color: rgb(149, 149, 151)">上传头像</span>
      </div>
    </template>
    <template #file="{ file }">
      <img class="el-upload-list__item-thumbnail" :src="file.url" fit="contain" />

      <span class="el-upload-list__item-actions">
        <span class="el-upload-list__item-preview" @click="handleUploadRef.$el.click()">
          <my-icon icon="el-Edit" />
          <span>更换头像</span>
        </span>
      </span>
    </template>
  </el-upload>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'

import type { UploadInstance, UploadRequestOptions, UploadUserFile } from 'element-plus'
import type { IHooksOptions } from '@/hooks/useCrud/data'

import { useCrud } from '@/hooks/useCrud'

const avatarUrl = defineModel<string>()
const fileList = ref<UploadUserFile[]>([
  {
    name: 'avatar',
    url: avatarUrl.value,
  },
])

const state: IHooksOptions<null, null> = reactive({
  createdIsNeed: false,
  queryForm: null,
})
const { uploadHandle } = useCrud<null, null>(state)

const uploadRef = ref<UploadInstance>()
const handleUploadRef = ref()
const handleUpload = async (options: UploadRequestOptions) => {
  uploadRef.value!.clearFiles()
  const res = await uploadHandle(options.file)
  if (res) {
    uploadRef.value!.handleStart(options.file)
    avatarUrl.value = res
  } else {
    fileList.value = [...fileList.value]
  }
}

onMounted(() => {
  watch(
    () => fileList.value[0].url,
    (val) => {
      const ele = uploadRef.value?.$el.querySelector('.el-upload')

      const display = val ? 'none' : 'flex'
      ele.style.setProperty('--display', display)
    },
    { immediate: true, deep: true }
  )
})
</script>
<style lang="scss" scoped>
:deep().el-upload {
  --display: flex;
  display: var(--display);
}
</style>
